<template>
  <div class="driver-schedule-container">
    <!-- 下拉刷新容器 -->
    <div 
      class="pull-to-refresh-container"
      :class="{ 'refreshing': isRefreshing, 'pulling': isPulling }"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      ref="refreshContainer"
    >
      <!-- 下拉刷新指示器 -->
      <div class="pull-to-refresh-indicator" :style="{ transform: `translateY(${pullDistance}px)` }">
        <div class="refresh-icon">
          <svg v-if="!isRefreshing" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M4 4V9H4.58152M19.4185 9C19.4185 9 18.4452 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 11.3116 19.9134 10.6433 19.75 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <div v-else class="loading-spinner-small"></div>
        </div>
        <div class="refresh-text">
          <span v-if="isRefreshing">正在刷新...</span>
          <span v-else-if="pullDistance > 60">释放立即刷新</span>
          <span v-else>下拉刷新</span>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-wrapper" :style="{ transform: `translateY(${Math.max(0, pullDistance - 60)}px)` }">
        <!-- 页面标题 -->
        <header class="page-header">
          <h1 class="page-title">我的排班</h1>
          <div class="header-decoration"></div>
        </header>

        <!-- 空状态提示 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <div v-else-if="Object.keys(groupedSchedules).length === 0" class="empty-state">
          <div class="empty-icon">📅</div>
          <h2>暂无排班信息</h2>
          <p>您当前没有安排的班次</p>
        </div>

        <!-- 按日期分组的排班列表 -->
        <div v-else class="schedule-group-list">
          <div 
            v-for="(group, date) in groupedSchedules" 
            :key="date" 
            class="schedule-group"
          >
            <!-- 日期标题 -->
            <div class="date-header">
              <div class="date-badge">
                <span class="date-day">{{ getDayOfMonth(date) }}</span>
                <span class="date-month">{{ getMonth(date) }}</span>
              </div>
              <div class="date-info">
                <h2 class="date-title">{{ formatDate(date) }}</h2>
                <p class="schedule-count">{{ group.length }}个班次</p>
              </div>
            </div>

            <!-- 当天的排班卡片列表 -->
            <div class="day-schedule-list">
              <div 
                v-for="item in group" 
                :key="`${item.schedule.id}-${item.dateInfo.id}`" 
                class="schedule-card"
              >
                <!-- 线路信息 -->
                <div class="route-info">
                  <div class="route-badge" :class="getRouteClass(item.schedule.line)">
                    {{ getRouteIcon(item.schedule.line) }}
                  </div>
                  <div class="route-details">
                    <h3>{{ lineMap[item.schedule.line] || item.schedule.line }}</h3>
                  </div>
                </div>

                <!-- 车辆信息 -->
                <div class="bus-info">
                  <div class="info-item">
                    <span class="info-label">车牌号:{{ item.schedule.tBus.licensePlate }}</span>
                    <span class="info-label">荷载:{{ item.schedule.tBus.maxCapacity }}人</span>
                  </div>
                </div>

                <!-- 乘客信息 -->
                <div class="passenger-info">
                  <div v-if="hasPassengers(item)" class="passenger-summary">
                    <div class="passenger-count">
                      <span class="count-number">{{ item.dateInfo.tBusReservation.length }}</span>
                      <span class="count-label">位乘客</span>
                    </div>
                    <button 
                      class="view-passengers-btn"
                      @click="openPassengerModal(item.dateInfo.tBusReservation)"
                    >
                      查看详情
                      <span class="btn-arrow">→</span>
                    </button>
                  </div>
                  <div v-else class="no-passengers">
                    <span class="no-passenger-icon">👥</span>
                    <span>暂无乘客预约</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 乘客信息弹窗 -->
    <teleport to="body">
      <transition name="modal-fade">
        <div v-if="showPassengerModal" class="modal-overlay" @click="closePassengerModal">
          <div class="modal-content" @click.stop>
            <div class="modal-header">
              <h3>乘客预约信息</h3>
              <button class="close-button" @click="closePassengerModal">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </button>
            </div>
            <div class="modal-body">
              <div v-if="currentPassengers.length > 0" class="passenger-list">
                <div 
                  v-for="passenger in currentPassengers" 
                  :key="passenger.id" 
                  class="passenger-card"
                >
                    <!-- <div class="passenger-avatar">
                      {{ passenger.realname ? passenger.realname.slice(-2) : '?' }}
                    </div> -->
                  <div class="passenger-details">
                    <h4>姓名：{{ passenger.realname }}</h4>
                    <div class="passenger-contact">
                      <div class="contact-item">
                        <span class="contact-label">手机号：{{ passenger.phone }}</span>
                        <span class="contact-value">学院：{{ passenger.collegeName }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-passengers">
                <div class="empty-icon">👥</div>
                <p>暂无乘客预约信息</p>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { getScheduleByDriverId } from "@/api/busmanagement/schedule";

// 响应式数据
const scheduleList = ref([]); // 存储排班信息
const showPassengerModal = ref(false); // 控制乘客信息弹窗的显示与隐藏
const currentPassengers = ref([]); // 当前弹窗显示的乘客信息
const loading = ref(true); // 加载状态

// 下拉刷新相关状态
const isRefreshing = ref(false); // 是否正在刷新
const isPulling = ref(false); // 是否正在下拉
const pullDistance = ref(0); // 下拉距离
const startY = ref(0); // 开始触摸的Y坐标
const refreshContainer = ref(null); // 刷新容器引用

// 线路映射对象
const lineMap = {
  1: "上午-青州→潍坊",
  2: "下午-青州→潍坊",
  3: "上午-潍坊→青州",
  4: "下午-潍坊→青州",
};

// 获取线路图标
const getRouteIcon = (line) => {
  const icons = {
    1: "🌅",
    2: "🌆",
    3: "🌅",
    4: "🌆",
  };
  return icons[line] || "🚌";
};

// 获取线路样式类
const getRouteClass = (line) => {
  const classes = {
    1: "morning-qingzhou",
    2: "afternoon-qingzhou",
    3: "morning-weifang",
    4: "afternoon-weifang",
  };
  return classes[line] || "default-route";
};

// 按日期分组的排班信息
const groupedSchedules = computed(() => {
  const groups = {};
  
  scheduleList.value.forEach((item) => {
    const date = item.dateInfo.departureData;
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item);
  });
  
  return groups;
});

// 检查是否有乘客
const hasPassengers = (item) => {
  return (
    item.dateInfo &&
    item.dateInfo.tBusReservation &&
    item.dateInfo.tBusReservation.length > 0
  );
};

// 打开乘客信息弹窗
const openPassengerModal = (passengers) => {
  currentPassengers.value = passengers;
  showPassengerModal.value = true;
  // 防止背景滚动
  document.body.style.overflow = "hidden";
};

// 关闭乘客信息弹窗
const closePassengerModal = () => {
  showPassengerModal.value = false;
  currentPassengers.value = [];
  // 恢复背景滚动
  document.body.style.overflow = "";
};

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  // 判断是否是今天或明天
  const isToday = date.toDateString() === today.toDateString();
  const isTomorrow = date.toDateString() === tomorrow.toDateString();

  if (isToday) {
    return "今天";
  } else if (isTomorrow) {
    return "明天";
  } else {
    return date.toLocaleDateString("zh-CN", {
      month: "short",
      day: "numeric",
      weekday: "short",
    });
  }
};

// 获取月份
const getMonth = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", { month: "short" });
};

// 获取日期
const getDayOfMonth = (dateString) => {
  const date = new Date(dateString);
  return date.getDate();
};

// 获取排班数据的函数
const fetchScheduleData = async () => {
  try {
    const driverId = 192; // 示例driverId，实际应从用户信息中获取
    const response = await getScheduleByDriverId(driverId);
    
    if (response.code === 200 && response.data) {
      // 过滤掉今天以前的数据并扁平化处理
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 设置为当天的开始

      const flattenedData = [];
      
      // 遍历每个排班
      response.data.forEach((schedule) => {
        // 遍历每个排班的日期和预约信息
        if (schedule.dateAndReservation && Array.isArray(schedule.dateAndReservation)) {
          schedule.dateAndReservation.forEach((dateInfo) => {
            if (dateInfo.departureData) {
              const departureDate = new Date(dateInfo.departureData);
              // 只保留今天及以后的日期
              if (departureDate >= today) {
                flattenedData.push({
                  schedule: schedule,
                  dateInfo: dateInfo
                });
              }
            }
          });
        }
      });

      // 按日期排序
      scheduleList.value = flattenedData.sort((a, b) => {
        const dateA = new Date(a.dateInfo.departureData);
        const dateB = new Date(b.dateInfo.departureData);
        return dateA - dateB;
      });
    }
  } catch (error) {
    console.error("获取排班信息失败:", error);
  }
};

// 下拉刷新相关函数
const handleTouchStart = (e) => {
  // 如果已经在刷新中，不处理
  if (isRefreshing.value) return;
  
  // 记录开始触摸的位置
  startY.value = e.touches[0].clientY;
  isPulling.value = true;
};

const handleTouchMove = (e) => {
  // 如果不在下拉状态或已经在刷新中，不处理
  if (!isPulling.value || isRefreshing.value) return;
  
  const currentY = e.touches[0].clientY;
  const distance = currentY - startY.value;
  
  // 只有向下拉且页面在顶部时才处理
  if (distance > 0 && window.scrollY === 0) {
    // 阻止默认的滚动行为
    e.preventDefault();
    
    // 限制最大下拉距离
    pullDistance.value = Math.min(distance * 0.5, 120); // 0.5是阻尼系数，让下拉感觉更自然
  }
};

const handleTouchEnd = async () => {
  // 如果不在下拉状态，不处理
  if (!isPulling.value) return;
  
  // 如果下拉距离超过阈值，触发刷新
  if (pullDistance.value > 60) {
    await performRefresh();
  } else {
    // 否则回弹
    pullDistance.value = 0;
  }
  
  isPulling.value = false;
};

// 执行刷新操作
const performRefresh = async () => {
  isRefreshing.value = true;
  pullDistance.value = 60; // 固定在刷新位置
  
  try {
    // 重新获取数据
    await fetchScheduleData();
  } catch (error) {
    console.error("刷新数据失败:", error);
  } finally {
    // 刷新完成，重置状态
    isRefreshing.value = false;
    pullDistance.value = 0;
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  try {
    await fetchScheduleData();
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
/* 基础容器样式 */
.driver-schedule-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  color: #333;
  background-color: #f8fafc;
  min-height: 100vh;
  overflow-x: hidden;
}

/* 下拉刷新容器 */
.pull-to-refresh-container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

/* 下拉刷新指示器 */
.pull-to-refresh-indicator {
  position: absolute;
  top: -60px;
  left: 0;
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8fafc;
  transition: transform 0.3s ease;
  z-index: 10;
}

.refresh-icon {
  margin-right: 8px;
  color: #4299e1;
  display: flex;
  align-items: center;
}

.loading-spinner-small {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(66, 153, 225, 0.2);
  border-top: 2px solid #4299e1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.refresh-text {
  font-size: 14px;
  color: #4a5568;
}

/* 内容区域 */
.content-wrapper {
  transition: transform 0.3s ease;
  padding: 20px;
  padding-bottom: 40px;
}

/* 页面标题 */
.page-header {
  margin-bottom: 30px;
  text-align: center;
  position: relative;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin: 0;
  position: relative;
  display: inline-block;
}

.header-decoration {
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #4299e1, #667eea);
  margin: 12px auto 0;
  border-radius: 2px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(66, 153, 225, 0.2);
  border-top: 4px solid #4299e1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #718096;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.7;
}

.empty-state h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px;
  color: #4a5568;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
  color: #718096;
}

/* 排班组列表 */
.schedule-group-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 排班组 */
.schedule-group {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
}

/* 日期标题 */
.date-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #1bbee7, #46a0e9);
  color: white;
  gap: 16px;
}

.date-badge {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  flex-shrink: 0;
}

.date-day {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.date-month {
  font-size: 12px;
  text-transform: uppercase;
  opacity: 0.9;
}

.date-info {
  flex: 1;
}

.date-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 4px;
}

.schedule-count {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

/* 当天的排班列表 */
.day-schedule-list {
  display: flex;
  flex-direction: column;
  gap: 1px;
  background: #e2e8f0;
}

/* 排班卡片 */
.schedule-card {
  background: white;
  padding: 20px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.schedule-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

/* 线路信息 */
.route-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}

.route-badge {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.morning-qingzhou {
  background: linear-gradient(135deg, #f6d365, #fda085);
}

.afternoon-qingzhou {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.morning-weifang {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.afternoon-weifang {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.default-route {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.route-details h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #1a202c;
}

/* 车辆信息 */
.bus-info {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: #718096;
}

.info-value {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
}

/* 乘客信息 */
.passenger-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.passenger-count {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  color: #4299e1;
}

.count-label {
  font-size: 14px;
  color: #718096;
}

.view-passengers-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #edf2f7;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  cursor: pointer;
  transition: background 0.2s;
}

.view-passengers-btn:hover {
  background: #e2e8f0;
}

.btn-arrow {
  transition: transform 0.2s;
}

.view-passengers-btn:hover .btn-arrow {
  transform: translateX(2px);
}

.no-passengers {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #a0aec0;
  font-size: 14px;
}

.no-passenger-icon {
  font-size: 18px;
  opacity: 0.7;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #1a202c;
}

.close-button {
  background: none;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #718096;
  transition: background 0.2s, color 0.2s;
}

.close-button:hover {
  background: #f7fafc;
  color: #2d3748;
}

.modal-body {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

/* 乘客列表 */
.passenger-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.passenger-card {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: #f7fafc;
  border-radius: 8px;
  transition: background 0.2s;
}

.passenger-card:hover {
  background: #edf2f7;
}

.passenger-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  flex-shrink: 0;
}

.passenger-details {
  flex: 1;
}

.passenger-details h4 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 4px;
  color: #1a202c;
}

.passenger-details p {
  font-size: 14px;
  margin: 0 0 2px;
  color: #4a5568;
}

/* 乘客联系方式样式 */
.passenger-contact {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contact-label {
  color: #718096;
  font-size: 14px;
}

.contact-value {
  color: #2d3748;
  font-size: 14px;
  font-weight: 500;
  text-align: right;
}

.empty-passengers {
  text-align: center;
  padding: 40px 20px;
  color: #718096;
}

.empty-passengers .empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.7;
}

/* 弹窗动画 */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .driver-schedule-container {
    padding: 0;
  }
  
  .content-wrapper {
    padding: 16px;
    padding-bottom: 40px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .date-header {
    padding: 16px;
  }
  
  .date-badge {
    width: 50px;
    height: 50px;
  }
  
  .date-day {
    font-size: 20px;
  }
  
  .date-title {
    font-size: 18px;
  }
  
  .schedule-card {
    padding: 16px;
  }
  
  .route-badge {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .route-details h3 {
    font-size: 16px;
  }
  
  .modal-content {
    margin: 0;
    border-radius: 12px 12px 0 0;
    max-height: 90vh;
  }
}
</style>
